//
//  RechargeViewController.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/9/23.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "RechargeViewController.h"
#import "CYScanCodeVC.h"
#import "CYOnlineScanVC.h"
#import "CYRechargeHeaderView.h"
#import "CYTotalRechargeModel.h"
#import "CYThirdXMLModel.h"
#import "CYXMLReader.h"
#import "CYWebViewController.h"
#import "CYPickerController.h"
@interface RechargeViewController ()<CYOnlineScanDelegate>
@property (nonatomic, strong) UISegmentedControl *seg;
@property (nonatomic, strong) CYView *line;
@property (nonatomic, strong) UIScrollView *scrollview;
@property (nonatomic, strong) CYScanCodeVC *scanCodeVC;
@property (nonatomic, strong) CYOnlineScanVC *onlineCodeVC;
@property (nonatomic, strong) CYRechargeHeaderView *headerView;
@property (nonatomic, strong) CYPickerController *dateList;//时间列表
@property (nonatomic, strong) CYView *alphaView;//时间列表的背景
@property (nonatomic, copy) NSString *scheme;//应用内跳转urlscheme
@property (nonatomic, strong) CYTotalRechargeModel *totalModel;//在线扫码接口id 的model ,是公司的服务器返回的
@property (nonatomic, strong) CYThirdXMLModel *xmlModel;//微信／支付宝／QQ的在线扫描二维码模型,是第三方返回的
@end

@implementation RechargeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.scrollview.hidden = NO;
    self.seg.hidden = (_type == WeixinType || _type == AlipayType || _type == QQType)?NO:YES;
    self.headerView.hidden = (_type == OnlineType || _type == OnlineBankType)?NO:YES;
    self.line.hidden = (_type == OnlineType || _type == OnlineBankType)?YES:NO;
    self.scanCodeVC.hidden = (_type == WeixinType || _type == AlipayType || _type == QQType)?NO:YES;
    self.onlineCodeVC.hidden = (_type == OnlineType || _type == OnlineBankType)?NO:YES;
    
    // Do any additional setup after loading the view.
}

- (UISegmentedControl *)seg{
    if (!_seg) {
        _seg = [[UISegmentedControl alloc]initWithItems:@[@"扫码转账",@"在线扫码转账"]];
        _seg.selectedSegmentIndex = 0;
        _seg.tintColor = ORANGE_COLOR;
        [self.scrollview addSubview:_seg];
        [_seg addTarget:self action:@selector(actionForSeg:) forControlEvents:UIControlEventValueChanged];
        
        [_seg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_scrollview).with.offset(AL(PT(20)));
            make.centerX.equalTo(_scrollview);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - AL(PT(60)) * 2, AL(PT(60))));
        }];
    }
    return _seg;
}

- (CYView *)line{
    if (!_line) {
        _line = [[CYView alloc]initWithColor:LINE_COLOR];
        [self.scrollview addSubview:_line];
        
        [_line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_seg.mas_bottom).with.offset(AL(PT(20)));
            make.centerX.equalTo(_scrollview);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, AL(PT(12))));
        }];
    }
    return _line;
}

- (UIScrollView *)scrollview{
    if (!_scrollview) {
        _scrollview = [[UIScrollView alloc]init];
        _scrollview.showsVerticalScrollIndicator = NO;
        _scrollview.bounces = NO;
        [self.view addSubview:_scrollview];
        
        [_scrollview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).with.offset(NAVIBAR_HEIGHT + STATUS_HEIGHT);
            make.bottom.equalTo(self.view).with.offset(0);
            make.centerX.equalTo(self.view);
            make.width.mas_equalTo(SCREEN_WIDTH);
        }];
    }
    return _scrollview;
}

- (CYScanCodeVC *)scanCodeVC{
    if (!_scanCodeVC) {
        WS(self)
        _scanCodeVC = [[CYScanCodeVC alloc]initWithTitle:self.title block:^(ScanCodeEvent event, id data) {
            [weakSelf methodForscanCode:event dict:data];
        }];
        [self.scrollview addSubview:_scanCodeVC];
        
        [_scanCodeVC mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(SCREEN_WIDTH);
            make.centerX.equalTo(_scrollview);
            make.top.equalTo(_line.mas_bottom).with.offset(0);
            make.bottom.equalTo(_scrollview);
        }];
    }
    return _scanCodeVC;
}

- (CYOnlineScanVC *)onlineCodeVC{
    if (!_onlineCodeVC) {
        WS(self)
        _onlineCodeVC = [[CYOnlineScanVC alloc]initWithTitle:self.title block:^(OnlineScanEvent event, id data) {
            [weakSelf methodForOnlineScan:event dict:data];
        }];
        _onlineCodeVC.delegate = self;
        [self.scrollview addSubview:_onlineCodeVC];
        
        [_onlineCodeVC mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(SCREEN_WIDTH);
            make.centerX.equalTo(_scrollview);
            make.top.equalTo(_line.mas_bottom).with.offset(0);
            make.bottom.equalTo(self.view);
        }];
    }
    return _onlineCodeVC;
}

- (CYRechargeHeaderView *)headerView{
    if (!_headerView) {
        _headerView = [[CYRechargeHeaderView alloc] init];
        _headerView.userName = _personalData[@"username"];
        _headerView.money = [_personalData[@"coin"] floatValue];
        [self.view addSubview:_headerView];
        
        [_headerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsMake(NAVIBAR_HEIGHT + STATUS_HEIGHT, 0,
                                                   SCREEN_HEIGHT - NAVIBAR_HEIGHT - STATUS_HEIGHT - _headerView.bounds.size.height, 0));
        }];
    }
    return _headerView;
}

- (CYView *)alphaView{
    if (!_alphaView) {
        _alphaView = [[CYView alloc]initWithColor:[UIColor clearColor]];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(actionForSigleTap)];
        [_alphaView addGestureRecognizer:tap];
        [self.view addSubview:_alphaView];
        
        [_alphaView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsMake(NAVIBAR_HEIGHT + STATUS_HEIGHT, 0, 0, 0));
        }];
    }
    return _alphaView;
}

- (CYPickerController *)dateList{
    if (!_dateList) {
        WS(self)
        _dateList = [[CYPickerController alloc]initWithBlock:^(NSString *data, NSInteger type, NSString *cancelOrEnter) {
            if (type == 0)//默认为时间选择
                [weakSelf setupTime:(NSString *)data action:cancelOrEnter];
        }];
        [self.alphaView addSubview:_dateList];
        
        [_dateList mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_alphaView.mas_bottom).with.offset(0);
            make.centerX.equalTo(_alphaView);
            make.size.mas_equalTo(_dateList.bounds.size);
        }];
    }
    return _dateList;
}

- (void)setType:(RechargeType)type{
    if (_type != type) {
        _type = type;
        if (_type == WeixinType){
            self.title = @"微信";
            self.scheme = @"weixin://";
        }else if (_type == AlipayType){
            self.title = @"支付宝";
            self.scheme = @"alipay://";
        }else if (_type == QQType){
            self.title = @"QQ";
            self.scheme = @"mqq://";
        }else if (_type == OnlineType){
            self.title = @"在线充值";
            self.scheme = nil;
        }else if (_type == OnlineBankType){
            self.title = @"网银快捷充值";
            self.scheme = nil;
        }
    }
}

- (void)setXmlModel:(CYThirdXMLModel *)xmlModel{
    if (_xmlModel != xmlModel) {
        _xmlModel = xmlModel;
        [_onlineCodeVC showQRCodeWithXMLModel:xmlModel];
    }
}

- (void)actionForSeg:(UISegmentedControl *)sender{
    _scrollview.scrollEnabled = (sender.selectedSegmentIndex == 0)?YES:NO;
    _onlineCodeVC.hidden = (sender.selectedSegmentIndex == 0)?YES:NO;
    _scanCodeVC.hidden = (sender.selectedSegmentIndex == 0)?NO:YES;
}

//扫码转账block——method
- (void)methodForscanCode:(ScanCodeEvent)event dict:(id)dict{
    if (event == saveForScanCodeEvent)
        [self writeToSavedPhotos:dict];
    else if (event == jumpForScanCodeEvent)
        [self jumpToAppWithURLScheme:self.scheme];
    else if (event == showDateListForScanCodeEvent)
        [self showDateList];
}

//在线扫码转账block--method
- (void)methodForOnlineScan:(OnlineScanEvent)event dict:(id)dict{
    if (event == saveForOnlineScanEvent)
        [self writeToSavedPhotos:dict];
    else if (event == jumpForOnlineScanEvent)
        [self jumpToAppWithURLScheme:self.scheme];
    else if (event == subMitForOnlineScanEvent){
    }
}

//应用内跳转
- (void)jumpToAppWithURLScheme:(NSString *)scheme{
    if([[AppDelegate shareAppDelegate] openURL:scheme] == NO)
        [CYAlert showInWindowWithTitle:@"提示" message:@"请确认是否已经安装APP" enterComplete:^{
            [[AppDelegate shareAppDelegate] openURL:@"itms-apps://App.apple.com"];
        }];
}

//保存到相册
- (void)writeToSavedPhotos:(UIImage *)image{
    if (image)
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
    else
        [CYHUD show:@"图片错误"];
}

//保存到相册的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error){
        if (error.code == -3310) {
            [CYAlert showInWindowWithTitle:nil message:@"您的应用没有访问相册权限，需要打开吗？" enterComplete:^{
                [[AppDelegate shareAppDelegate] openURL:UIApplicationOpenSettingsURLString];
            }];
        }
    }
    else
        [CYHUD show:@"二维码已经保存到相册..."];
}

//扫码充值请求
- (void)httpsScanCode{
    
    
}

//设置存款时间
- (void)setupTime:(NSString *)time action:(NSString *)cancelOrEnter{
    _scanCodeVC.timeField.text = [NSString insertYearWithDateString:time];//转换成带年的时间
    if (cancelOrEnter){
        _alphaView.hidden = YES;
        _scanCodeVC.timeField.text = ([cancelOrEnter isEqualToString:@"cancel"])?@"":_scanCodeVC.timeField.text;
        [_scanCodeVC.timeField resignFirstResponder];//注意这里要放弃第一响应身份
        [UIView animateWithDuration:0.3 animations:^{
            _scanCodeVC.transform  = CGAffineTransformIdentity;
        }];
        return;
    }
}

//弹出时间选择器
- (void)showDateList{
    self.alphaView.hidden = NO;
    //时间输入框在当前屏幕的纵向坐标最大值maxY
    CGFloat originMaxY = CGRectGetMaxY([_scanCodeVC.timeField convertRect:_scanCodeVC.timeField.bounds toView:[[[UIApplication sharedApplication] delegate] window]]);
    //判断是非遮挡当前输入框，大于0遮挡，小于0没有
    CGFloat map = originMaxY + self.dateList.bounds.size.height -  SCREEN_HEIGHT;
    
    [UIView animateWithDuration:0.3 animations:^{
        if (map > 0)
            _scanCodeVC.transform = CGAffineTransformMakeTranslation(0, -map);
        self.dateList.transform = CGAffineTransformMakeTranslation(0, - _dateList.bounds.size.height);
    }];
}

//半透明背景单击触摸手势响应方法
- (void)actionForSigleTap{
    [UIView animateWithDuration:0.3 animations:^{
        _scanCodeVC.transform  = CGAffineTransformIdentity;
        _dateList.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        _alphaView.hidden = YES;
    }];
}

- (void)httpsQRCode:(NSString *)money {
    int payID = 0;
    if (_type == WeixinType)
        payID = _totalModel.wxPay.ID;
    else if (_type == QQType)
        payID = _totalModel.qqqbPay.ID;
    else if (_type == AlipayType)
        payID = _totalModel.zfbPay.ID;
    else if (_type == OnlineBankType)
        payID = _totalModel.kjPay.ID;
    int codeID = (_type == OnlineBankType)?_totalModel.kjPay.ID:_model.ID;
    //请求体
    NSDictionary *para = @{@"username":[CYUser shareUser].username, @"token":[CYUser shareUser].token,
                           @"price":money,//金额
                           @"code_id":@(codeID),//支付类型
                           @"payInfoId":@(payID)};//支付接口id
    NSString *api = (_type == OnlineBankType)?API_quickPay:API_online_scan;//根据类型，选择接口
    self.task = [CYHttps POST:api parameters:para showHUD:NO progress:nil success:^(id data) {
        if (_type != OnlineBankType){
            NSDictionary *dict = [CYXMLReader readerWithXMLString:data];
            DeLog(@"xml dict  %@",dict);
            self.xmlModel = [CYThirdXMLModel mj_objectWithKeyValues:dict];
        }
        else{
            CYWebViewController *webview = [[CYWebViewController alloc]init];//快捷键支付，退出webview
            //            webview.postDic = data;
            [self.navigationController pushViewController:webview animated:YES];
        }
    } failure:nil];
}

#pragma - mark - CYOnlineScanDelegate - method
- (id)httpsWithMoney:(NSString *)money{
    NSDictionary *para = @{@"username":[CYUser shareUser].username, @"token":[CYUser shareUser].token};
    NSString *api = (_type == OnlineBankType)?API_quickUser:API_pay_ID;//根据类型，选择接口
    self.spareTask = [CYHttps POST:api parameters:para showHUD:YES progress:nil success:^(id data) {
        if (data){
            _totalModel = [CYTotalRechargeModel mj_objectWithKeyValues:data];
            [self httpsQRCode:money ];
        }
    } failure:nil];
    return nil;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    _scanCodeVC.model = _model;
    _onlineCodeVC.model = _model;
}
- (void)setupNavigationBarTintColor:(UIColor *)color{
    [super setupNavigationBarTintColor:color];
    self.navigationController.navigationItem.title = self.title;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
